103E - Buying Sets - CodeForces Solution


flows graph matchings *2900

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
#define pb push_back
#define MP make_pair
#define pii pair<int,int>
#define fi first
#define se second
using namespace std;
typedef long long ll;
template<typename T>void readmain(T &x){
    bool neg=false;unsigned int c=getchar();
    for(;(c^48)>9;c=getchar())if(c=='-')neg=true;
    for(x=0;(c^48)<10;c=getchar())x=(x<<3)+(x<<1)+(c^48);
    if(neg)x=-x;
}
template<typename T>T& read(T &x){readmain(x);return x;}
template<typename T,typename ...Tr>void read(T &x,Tr&... r){readmain(x);read(r...);}
constexpr int N=605,M=130005;
constexpr ll inf=1e9;
int n,m,s,t,MAXN;
namespace MAXFLOW{
	int edgenum=1,head[N],cur[N],Next[M*2],vet[M*2],dis[N];
	ll flw[M*2],INF=1e18;
	queue<int> q;
	void add(int u,int v,ll w){
		edgenum++;
		Next[edgenum]=head[u];
		vet[edgenum]=v;
		flw[edgenum]=w;
		head[u]=edgenum;
	}
	void ADD(int u,int v,ll w){add(u,v,w);add(v,u,0);}
	bool bfs(int s,int t){
		for(int i=1;i<=MAXN;i++)cur[i]=head[i],dis[i]=-1;
		while(!q.empty())q.pop();
		q.push(s);dis[s]=1;
		while(!q.empty()){
			int u=q.front();
			q.pop();
			for(int e=head[u];e;e=Next[e]){
				int v=vet[e];
				if(flw[e]>0&&dis[v]==-1){
					dis[v]=dis[u]+1;
					if(v==t)return 1;
					q.push(v);
				}
			}
		}
		return 0;
	}
	ll dfs(int u,int t,ll flow){
		if(!flow||u==t)return flow;
		ll used=0;
		for(int e=cur[u];e;e=Next[e]){
			int v=vet[e];cur[u]=e;
			if(dis[v]==dis[u]+1){
				ll tmp=dfs(v,t,min(flow-used,flw[e]));
				if(tmp==0)continue;
				flw[e]-=tmp;flw[e^1]+=tmp;
				used+=tmp;
				if(flow==used)break;
			}
		}
		return used;
	}
	ll dinic(int s,int t){ll FLOW=0;while(bfs(s,t))FLOW+=dfs(s,t,INF);return FLOW;}
}
using MAXFLOW::ADD,MAXFLOW::dinic;
ll ans;
int main(){
    read(n);
    s=n+n+1,t=s+1,MAXN=t;
    for(int i=1;i<=n;i++){
        int x;read(x);
        for(int j=1;j<=x;j++){
            int y;read(y);
            ADD(i,y+n,inf);
        }
    }
    for(int i=1;i<=n;i++){
        int x;read(x);ans+=x;
        ADD(s,i,inf-x);
        ADD(i+n,t,inf);
    }
    printf("%lld\n",ans-((ll)inf*n-dinic(s,t)));
    return 0;
}


Comments

Submit
0 Comments
More Questions

706B - Interesting drink
1265A - Beautiful String
214A - System of Equations
287A - IQ Test
1108A - Two distinct points
1064A - Make a triangle
1245C - Constanze's Machine
1005A - Tanya and Stairways
1663F - In Every Generation
1108B - Divisors of Two Integers
1175A - From Hero to Zero
1141A - Game 23
1401B - Ternary Sequence
598A - Tricky Sum
519A - A and B and Chess
725B - Food on the Plane
154B - Colliders
127B - Canvas Frames
107B - Basketball Team
245A - System Administrator
698A - Vacations
1216B - Shooting
368B - Sereja and Suffixes
1665C - Tree Infection
1665D - GCD Guess
29A - Spit Problem
1097B - Petr and a Combination Lock
92A - Chips
1665B - Array Cloning Technique
1665A - GCD vs LCM